//普通商户模式下单
function unifiedorder(params) {
	if (objIsEmpty(params)) {
		console.log('参数为空');
		return null
	}
	if (objIsEmpty(params.orderId)) {
		console.log('orderId为空');
		return null
	}
	if (objIsEmpty(params.openid)) {
		console.log('openid为空');
		return null
	}
	if (objIsEmpty(params.amount)) {
		console.log('amount为空');
		return null
	}
	if (objIsEmpty(params.title)) {
		console.log('title为空');
		return null
	}
	params.type = 2
	return new Promise((resolve, reject) => {
		// 1.调用下单
		uniCloud.callFunction({
			name: 'zhy-mp-alipay',
			data: params,
			success(res) {
				console.log('支付宝统一下单成功:' + JSON.stringify(res));
				if (res != null && res.result != null && res.result.traceId != null) {
					console.log('11111');
					resolve(res)
				} else {
					console.log('00000');
					reject(res)
				}
			},
			fail(err) {
				//{"errMsg":"request:fail http status error","errCode":"SYS_ERR","code":"SYS_ERR"}
				err.message = err.errMsg
				console.log('统一下单失败:' + JSON.stringify(err));
				reject(err)
			},
			/* complete(res) {
				console.log('统一下单完成:' + JSON.stringify(res));
				if (res != null && res.result != null && res.result.traceId != null) {
					console.log('11111');
					resolve(res)
				} else {
					console.log('00000');
					reject(res)
				}
			} */
		})
	})
}

function objIsEmpty(obj) {
	if (obj == undefined || obj == '' || obj == null || JSON.stringify(obj) == '{}') {
		return true
	}
	return false
}

function businessRecharge(data) {
	/*
	{
	    "code": "10000",
	    "msg": "Success",
	    "outTradeNo": "bs220240606120609899029",
	    "tradeNo": "2024060622001452921428638338",
	    "traceId": "0b46a7e517176467708797669e282c",
	    "orderId": "bs220240606120609899029",
	    "amountFen": 1
	}
	*/
	console.log('发起支付');
	console.log(data);
	return new Promise((resolve, reject) => {
		my.tradePay({
			tradeNO: data.tradeNo,
			success: function(res) {
				// 成功失败都在这，需要根据条件去判断。resultCode=9000是订单处理成功。不能代表是支付成功！。notify中判断
				/* {
				  "tradeNo": "2023062622001487971409984441",
				  "result": "partner=\"\"&biz_type=\"\"&biz_sub_type=\"\"&trade_no=\"2023062622001487971409984441\"&app_name=\"alipay\"&display_pay_result=\"true\"&appenv=\"appid=alipay^system=ios^version=10.3.80.6000\"&success=\"true\"",
				  "resultCode": "9000"
				} */
				/*
				{"resultCode":"6001","memo":"用户中途取消"}
				*/
				console.log(JSON.stringify(res));
				if (res.resultCode === '9000') {
					console.log('订单处理成功...');
					resolve(res)
				} else {
					// 失败
					res.errMsg = 'resultCode:' + res.resultCode + ',memo:' + res.memo
					reject(res)
				}
				resolve(1)
			},
			fail: function(err) {
				console.log('支付失败');
				console.log(JSON.stringify(err));
				res.errMsg = JSON.stringify(err)
				reject(err)
			}
		})
	})
}

// https://opendocs.alipay.com/open/62987723_alipay.fund.trans.uni.transfer?pathHash=66064890&ref=api&scene=ca56bca529e64125a2786703c6192d41
// alipay.fund.trans.uni.transfer 单笔转账接口
function userWithdrawToCash(params) {
	const app = getApp()
	if (objIsEmpty(params)) {
		console.log('参数为空');
		return null
	}
	if (objIsEmpty(params.out_batch_no)) {
		console.log('out_batch_no为空');
		return null
	}
	if (objIsEmpty(params.batch_name)) {
		console.log('batch_name为空');
		return null
	}
	if (objIsEmpty(params.batch_remark)) {
		console.log('batch_remark为空');
		return null
	}
	if (objIsEmpty(params.total_amount)) {
		console.log('total_amount为空');
		return null
	}

	if (objIsEmpty(params.total_num)) {
		console.log('total_num为空');
		return null
	}
	if (objIsEmpty(params.transfer_detail_list) || params.transfer_detail_list.length == 0) {
		console.log('transfer_detail_list为空');
		return null
	}
	params.type = 3
	return new Promise((resolve, reject) => {
		// 1.调用提现:商家转账到零钱
		uniCloud.callFunction({
			name: 'zhy-mp-alipay',
			data: params,
			success(res) {
				// 还需要判断返回code:10000成功
				// {"result":{"msg":"Business Failed","code":"40004","subMsg":"参数有误trans_amount:不能为空","subCode":"INVALID_PARAMETER","traceId":"2196708317176551000714337eb209"}}
				console.log('提现结果:' + JSON.stringify(res));
				// 添加到用户提现记录表
				if (res != null && res.result != null && res.code == '10000') {
					console.log('提现成功');
					addWithdrawRecord(params, 1)
					resolve(res)
				} else {
					console.log('提现失败');
					if (res != null && res.result != null) {
						params.fail_reason = res.result.msg + ':' + res.result.subMsg
					}
					addWithdrawRecord(params, 0)
					reject(res)
				}
			},
			fail(err) {
				console.log('提现失败:' + JSON.stringify(err));
				params.fail_reason = '系统错误:' + JSON.stringify(err)
				addWithdrawRecord(params, 0)
				reject(err)
			},
			complete(res) {
				console.log('提现完成:' + JSON.stringify(res));
			}
		})
	})
}

function addWithdrawRecord(withdrawRecord, success) {
	const app = getApp()
	withdrawRecord.success = success
	withdrawRecord.withdraw_time = new Date().getTime()
	withdrawRecord.openid = uni.getStorageSync(app.globalData.session.userKey)
	withdrawRecord.plat = app.globalData.plat.mpalipay
	withdrawRecord.operateType = 1 // 新增
	// alipay不需要此参数
	let {
		transfer_detail_list,
		...aplipayWithdrawAdd
	} = withdrawRecord
	console.log(JSON.stringify(aplipayWithdrawAdd));
	uniCloud.callFunction({
		name: 'zhy-user-withdrawal-record',
		data: aplipayWithdrawAdd,
		success(res) {
			console.log('添加提取记录成功');
			console.log(JSON.stringify(res));
		},
		fail(err) {
			console.log('添加提取记录失败');
			console.log(JSON.stringify(err));
		}
	})
}


//服务商模式模式下单：服务商模式都是以partner开头
function partnerUnifiedorder(params) {
	if (objIsEmpty(params)) {
		console.log('参数为空');
		return null
	}
	if (objIsEmpty(params.orderId)) {
		console.log('orderId为空');
		return null
	}
	if (objIsEmpty(params.openid)) {
		console.log('openid为空');
		return null
	}
	if (objIsEmpty(params.amount)) {
		console.log('amount为空');
		return null
	}
	if (objIsEmpty(params.amountFen)) {
		console.log('amountFen为空');
		return null
	}
	if (objIsEmpty(params.title)) {
		console.log('title为空');
		return null
	}
	params.type = 4 //统一下单：分账
	return new Promise((resolve, reject) => {
		// 1.调用下单
		uniCloud.callFunction({
			name: 'zhy-mp-alipay',
			data: params,
			success(res) {
				console.log('分账统一下单成功-alipay:' + JSON.stringify(res));
				resolve(res)
			},
			fail(err) {
				console.log('分账统一下单失败--alipay:' + JSON.stringify(res));
				reject(err)
			}
		})
	})
}

function partnerPay(data) {
	return new Promise((resolve, reject) => {
		wx.requestPayment({
			timeStamp: data.timeStamp,
			nonceStr: data.nonceStr,
			package: data.package,
			signType: data.signType,
			paySign: data.paySign,
			success: function(res) {
				console.log('支付成功...');
				console.log(JSON.stringify(res));
				resolve(1)
			},
			fail: function(res) {
				console.log('支付失败');
				console.log(JSON.stringify(res));
				reject(res)
			},
			complete: function(res) {
				console.log('支付完成');
				console.log(JSON.stringify(res));
			}
		})
	})
}

// 分账
function partnerProfitSharing(params) {
	if (objIsEmpty(params)) {
		console.log('参数为空');
		return
	}
	params.type = 5 // 请求分账
	uniCloud.callFunction({
		name: 'zhy-mp-weixin',
		data: params,
		success(res) {
			console.log('发起分账成功');
			console.log(JSON.stringify(res));
		},
		fail(err) {
			console.log('发起分账失败');
			console.log(JSON.stringify(err));
		}
	})
}
// 查询分账结果
function partnerProfitSharing(params) {
	if (objIsEmpty(params)) {
		console.log('参数为空');
		return
	}
	params.type = 5 // 请求分账
	uniCloud.callFunction({
		name: 'zhy-mp-weixin',
		data: params,
		success(res) {
			console.log('发起分账成功');
			console.log(JSON.stringify(res));
		},
		fail(err) {
			console.log('发起分账失败');
			console.log(JSON.stringify(err));
		}
	})
}
module.exports = {
	unifiedorder,
	businessRecharge,
	userWithdrawToCash,
	partnerUnifiedorder,
	partnerPay,
	partnerProfitSharing
}